/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.raspberrypi.gpio.input;

import cn.hutool.core.io.FastByteArrayOutputStream;
import cn.hutool.core.io.IoUtil;
import com.pi4j.Pi4J;
import com.pi4j.context.Context;
import com.pi4j.exception.LifecycleException;
import com.pi4j.io.spi.Spi;
import com.pi4j.util.Console;
import lombok.AccessLevel;
import lombok.experimental.Accessors;
import lombok.experimental.FieldDefaults;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 * <b>(RaspberryPiTemperature)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2023/2/21
 */
@FieldDefaults(level = AccessLevel.PRIVATE)
@Accessors(chain = true)
@Controller
@Mapping("/temperaturexxx")
public class RaspberryPiTemperature {
    @Inject
    Context pi4j;
    static final int PIN_TEMPERATURE = 23;
    static final int PIN_BUTTON      = 26;

    Spi temperature;

    @Mapping("/")
    public void index(org.noear.solon.core.handle.Context ctx) {
        initTemperature();
        //内部跳转到 /index.htm
        ctx.forward("/raspberry/input/RaspberryPiTemperature.html");
    }

    @Mapping("/test")
    public void test() {
        System.out.println("开始测试温度");
        while (true) {
            if (temperature.read() == -1) {
                return;
            }
            FastByteArrayOutputStream outputStream = IoUtil.read(temperature.in());
            System.out.println(outputStream);
        }
    }

    private void initTemperature() {
        var     console = new Console();
        Context pi4j    = Pi4J.newAutoContext();
        console.title("<-- The Pi4J V2 Project Extension  -->", "DHT22_App");
        String helpString = " parms:  -d  data GPIO number  -t trace " + " \n -t  trace values : \"trace\", \"debug\", \"info\", \"warn\", \"error\" \n " + " or \"off\"  Default \"info\"";

        Signal.handle(new Signal("INT"), new SignalHandler() {
            public void handle(Signal sig) {
                System.out.println("Performing ctl-C shutdown");
                try {
                    pi4j.shutdown();
                } catch (LifecycleException e) {
                    e.printStackTrace();
                }
                System.exit(2);
            }
        });

        DHT22 sensor = new DHT22(pi4j, console, PIN_TEMPERATURE, "trace");
        sensor.readAndDisplayData();

        pi4j.shutdown();
    }
}
